package com.lcz.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.zaxxer.hikari.HikariDataSource;
import com.lcz.enums.DatabaseIdEnums;
import com.zhou.starter.jpacomment.config.JpaCommentAutoConfig;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.VendorDatabaseIdProvider;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author lcz
 * @desc mybatis 自动配置类
 * @mail lcz_0130@163.com
 * @date 2024/03/04
 */

@Configuration
@MapperScan("com.lcz.mapper")
public class MybatisAutoConfiguration {
    @Autowired
    private DataSource dataSource;

    /**
     * MyBatis Plus拦截器
     *
     * @return {@link MybatisPlusInterceptor}
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        String driverClassName = ((HikariDataSource) dataSource).getDriverClassName();
        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DatabaseIdEnums.getDbTypeByDriver(driverClassName)));

        return mybatisPlusInterceptor;
    }

    /**
     * 数据库id提供程序
     *
     * @return {@link DatabaseIdProvider}
     */
    @Bean
    public DatabaseIdProvider databaseIdProvider() {
        VendorDatabaseIdProvider databaseIdProvider = new VendorDatabaseIdProvider();
        Properties properties = new Properties();
        // 设置数据库厂商和databaseid别名
        for (DatabaseIdEnums databaseIdEnum : DatabaseIdEnums.values()) {
            // key=value
            // key     数据库厂商的databaseid
            // value   别名，和xml里面对应
            properties.put(databaseIdEnum.getName(), databaseIdEnum.getNameAlias());
        }
        databaseIdProvider.setProperties(properties);
        return databaseIdProvider;
    }


}
